/**
 * v-auth
 * 按钮权限指令
 */
import { useAuthStore } from "@/stores/modules/auth";
import type { Directive, DirectiveBinding } from "vue";

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    // 获取v-auth的值
    const { value } = binding;
    const authStore = useAuthStore();
    //获取当前页面的权限，buttonlist原是个对象，属性名为每个路由的name，authStore.routeName会获取当前路由的name，并把相应的权限赋值给currentPageRoles
    // const currentPageRoles = authStore.authButtonListGet[authStore.routeName] ?? [];
    //这里直接统一每个页面权限一致为后端返回的按钮权限数组
    // const currentPageRoles = (authStore.authButtonListGet?? [])as string[];
    const currentPageRoles = ['add', 'edit', 'delete', 'import', 'export'];
    //如果是数组写法
    if (value instanceof Array && value.length) {
      // bingding的vale中每一项是否都存在于后端返回的按钮权限数组
      const hasPermission = value.every(item => currentPageRoles.includes(item));
      // 只要有一个子元素不存在后端返回的按钮权限数组
      if (!hasPermission) el.remove();
    } else {
      //如果是字符串写法，值不存在于后端返回的按钮权限数组就移除按钮
      if (!currentPageRoles.includes(value)) el.remove();
    }
  }
};

export default auth;
